const cloud = require('wx-server-sdk')

cloud.init()

exports.main = async (event) => {
  const id = event.id;

  if (id == null) {
    return {
      code: -1
    };
  }

  const db = cloud.database();
  try {
    const out = await db.collection('deliveries').doc(id).get();
    let record;
    if (out.data._type == 'borrow') {
      const id = out.data.id;
      record = await db.collection('pool').doc(id).get();
    } else {
      record = await db.collection('records').doc(out.data.id).get();
    }
    const book = await db.collection('books').doc(record.data.book).get();
    out.data['record'] = record.data;
    out.data['book'] = book.data;
    return {
      code: 0,
      result: out.data
    };
  } catch (e) {
    return {
      code: -2,
      result: JSON.stringify(e)
    };
  }
}
